package com.atung.merchant.service.impl;

import com.atung.merchant.config.auth.AuthUserMangerContext;
import com.atung.merchant.dto.RevenueSeriesInfoEntity;
import com.atung.merchant.dto.StatisticRevenueEntity;
import com.atung.merchant.enums.MenuState;
import com.atung.merchant.enums.OrderState;
import com.atung.merchant.mapper.BusMerchantOrderMapper;
import com.atung.merchant.mapper.BusOrderMenuMapper;
import com.atung.merchant.po.BusMerchantOrder;
import com.atung.merchant.po.BusOrderMenu;
import com.atung.merchant.service.StatisticsService;
import com.atung.merchant.vo.StatisticDailyDataResponse;
import com.atung.merchant.vo.StatisticOrderResponse;
import com.atung.merchant.vo.StatisticRevenueResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
/**
 * @author Administrator
 */
public class StatisticsServiceImpl implements StatisticsService {

    @Resource
    private BusMerchantOrderMapper busMerchantOrderMapper;
    @Resource
    private BusOrderMenuMapper busOrderMenuMapper;

    @Override
    public StatisticOrderResponse statisticOrderService() {
        return null;
    }


    @Override
    public StatisticRevenueResponse statisticRevenueService() {
        Map<String, String> weekDateTemple = this.createWeekDateTemple();
        List<StatisticRevenueEntity> statisticRevenueEntities = busMerchantOrderMapper.queryWeekStatisticRevenue(AuthUserMangerContext.getMerchantId());
        statisticRevenueEntities.stream().forEach(item -> {
            weekDateTemple.put(item.getCreatorTime(), item.getTotalCollection());
        });
        // 将Map转换为List
        List<Map.Entry<String, String>> list = new ArrayList<>(weekDateTemple.entrySet());

        // 根据日期升序排序
        Collections.sort(list, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));

        // 格式化日期为MM-dd
        Map<String, String> sortedMap = new LinkedHashMap<>();
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat targetFormat = new SimpleDateFormat("MM-dd");
        for (Map.Entry<String, String> entry : list) {
            try {
                Date date = originalFormat.parse(entry.getKey());
                String formattedDate = targetFormat.format(date);
                sortedMap.put(formattedDate, entry.getValue());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
         return StatisticRevenueResponse.builder()
                .categories(sortedMap.keySet())
                .series(Arrays.asList(RevenueSeriesInfoEntity.builder().name("营收").data(sortedMap.values().stream().collect(Collectors.toList())).build()))
                .build();
    }

    @Override
    public StatisticDailyDataResponse statisticDailyDataService() {
        LocalDate today = LocalDate.now();
// 格式化今天的开始和结束时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.plusDays(1).atStartOfDay().minusSeconds(1);
// 将LocalDateTime转换为字符串
        String startOfDayStr = startOfDay.format(formatter);
        String endOfDayStr = endOfDay.format(formatter);
// 设置查询条件
        QueryWrapper<BusMerchantOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", AuthUserMangerContext.getMerchantId());
        queryWrapper.ge("creator_time", startOfDayStr);
        queryWrapper.lt("creator_time", endOfDayStr);
        List<BusMerchantOrder> busMerchantOrders = busMerchantOrderMapper.selectList(queryWrapper);

        //获取今日出餐数量
        QueryWrapper<BusOrderMenu> queryOrderMenuWrapper = new QueryWrapper<>();
        queryOrderMenuWrapper.eq("merchant_id", AuthUserMangerContext.getMerchantId());
        queryOrderMenuWrapper.eq("menu_state", MenuState.COMPLETE.ordinal());
        queryOrderMenuWrapper.ge("creator_time", startOfDayStr);
        queryOrderMenuWrapper.lt("creator_time", endOfDayStr);
        Long mealCount = busOrderMenuMapper.selectCount(queryOrderMenuWrapper).longValue();
        //金额收入
        BigDecimal reduce = busMerchantOrders.stream().map(BusMerchantOrder::getCollection).reduce(BigDecimal.ZERO, BigDecimal::add);
        long count = busMerchantOrders.stream().filter(item -> item.getState().equals(OrderState.COMPLETE.ordinal())).count();
        BigDecimal average = count > 0 ? reduce.divide(new BigDecimal(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;

        LocalDateTime date = LocalDateTime.now();
        // 格式化日期
        String formattedDate = date.format(DateTimeFormatter.ofPattern("hh:mm:ss"));
        return StatisticDailyDataResponse.builder()
                .averageTicket(average)
                .revenue(reduce.setScale(2, RoundingMode.HALF_UP))
                .orderCount(count)
                .mealCount(mealCount)
                .updateTime(formattedDate)
                .build();
    }


    public Map<String, String> createWeekDateTemple() {
        LocalDate today = LocalDate.now();
        // 存储最近七天日期的Map，键为日期，值为0
        Map<String, String> recentDaysMap = new LinkedHashMap<>();

        // 循环生成并添加最近七天的日期
        for (int i = 0; i < 7; i++) {
            // 计算日期
            LocalDate date = today.minusDays(i);
            // 格式化日期
            String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 将日期和值0添加到Map
            recentDaysMap.put(formattedDate, "0");
        }
        return recentDaysMap;
    }
}
